#!/usr/bin/python
# -*- coding:UTF8 -*-
import time

import pandas as pd
import requests
import json

# 10034129704071
productId = input("请输入商品编码:")

url = f'https://club.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98&productId={productId}&score=0&sortType=5&page=0&pageSize=10&isShadowSku=0&fold=1'
user_agent = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'}
r = requests.get(url=url, headers=user_agent).text
r = r.replace('fetchJSON_comment98(', '')
r = r.replace(');', '')
dict_cm = json.loads(r)
maxpage = dict_cm['maxPage']
# print(maxpage)
for maxpage in range(1, maxpage + 1):
    url = f'https://club.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98&productId={productId}&score=0&sortType=5&page={maxpage - 1}&pageSize=10&isShadowSku=0&fold=1'
    r = requests.get(url=url, headers=user_agent).text
    r = r.replace('fetchJSON_comment98(', '')
    r = r.replace(');', '')
    dict_cm = json.loads(r)
    comments = dict_cm['comments']
    contents = [contents['content'] for contents in comments]
    colors = [colors['productColor'] for colors in comments]
    size = [size['productSize'] for size in comments]
    times = [times['referenceTime'] for times in comments]
    # 写入数据
    datas = pd.DataFrame({
        '评论': contents,
        '颜色': colors,
        '尺寸': size,
        '评论时间': times,
    })
    # datas.index = datas.index + 1
    datas.to_csv('./测试数据/京东商品评价.csv', mode='a', header=0, encoding='ANSI',index=0)
    time.sleep(3)
